System.Array.FindIndex 方法 (T[], Int32, Int32, Predicate)

方法描述

搜索与指定谓词所定义的条件相匹配的一个元素,并返回 Array 中从指定的索引开始、包含指定元素个数的元素范围内第一个匹配项的从零开始的索引。

语法定义(C# System.Array.FindIndex 方法 (T[], Int32, Int32, Predicate) 的用法)

public static int FindIndex(
	T[] array,
	int startIndex,
	int count,
	Predicate match
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
array T[] 要搜索的从零开始的一维 Array。
startIndex System-Int32 从零开始的搜索的起始索引。
count System-Int32 要搜索的部分中的元素数。
match System-Predicate Predicate ,定义要搜索的元素的条件。
返回值 System.Int32 如果找到与 match 定义的条件相匹配的第一个元素,则为该元素的从零开始的索引;否则为 -1。

提示和注释

如果 count 大于 0,则在 Array 中向前搜索,从 startIndex 处开始,到 startIndex + count - 1 处结束。

Predicate 是对方法的委托,如果传递给它的对象与委托中定义的条件匹配,则该方法返回 true。 array 的元素被逐个传递给 Predicate

此方法的运算复杂度为 O(n),其中 n 是 count。

System.Array.FindIndex 方法 (T[], Int32, Int32, Predicate)例子

该方法重载返回 –1,因为在该范围内没有以“saurus”结尾的恐龙名称。

using System;

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = { "Compsognathus", 
            "Amargasaurus",   "Oviraptor",      "Velociraptor", 
            "Deinonychus",    "Dilophosaurus",  "Gallimimus", 
            "Triceratops" };

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine(
            "\nArray.FindIndex(dinosaurs, EndsWithSaurus): {0}", 
            Array.FindIndex(dinosaurs, EndsWithSaurus));

        Console.WriteLine(
            "\nArray.FindIndex(dinosaurs, 2, EndsWithSaurus): {0}",
            Array.FindIndex(dinosaurs, 2, EndsWithSaurus));

        Console.WriteLine(
            "\nArray.FindIndex(dinosaurs, 2, 3, EndsWithSaurus): {0}",
            Array.FindIndex(dinosaurs, 2, 3, EndsWithSaurus));
    }

    // Search predicate returns true if a string ends in "saurus".
    private static bool EndsWithSaurus(String s)
    {
        if ((s.Length > 5) && 
            (s.Substring(s.Length - 6).ToLower() == "saurus"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

/* This code example produces the following output:

Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops

Array.FindIndex(dinosaurs, EndsWithSaurus): 1

Array.FindIndex(dinosaurs, 2, EndsWithSaurus): 5

Array.FindIndex(dinosaurs, 2, 3, EndsWithSaurus): -1
 */

异常

异常 异常描述
ArgumentNullException
  • array 为 null。
  • match 为 null。
ArgumentOutOfRangeException
  • startIndex 超出了 array 的有效索引范围。
  • count 小于零。
  • startIndex 和 count 指定的不是 array 中的有效部分。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。